package chat

import (
	"context"
	"fmt"
	chatModel "gxcvu-ai/app/model/chat"

	"github.com/baidubce/bce-qianfan-sdk/go/qianfan"
	"github.com/gin-gonic/gin"
)

const (
	access_key = "dd32f7d2758a4123a2f2f8c8449b1a4e"
	secret_key = "a088dcd448864aa1b438da9b5aa95a45"
)

type QianFan struct {
}

func FormatChat(content string) qianfan.ChatCompletionMessage {
	return qianfan.ChatCompletionUserMessage(content)
}

func FormatChatMessage(messageData []chatModel.Message) (resp []qianfan.ChatCompletionMessage) {
	resp = []qianfan.ChatCompletionMessage{}
	for _, v := range messageData {
		fmt.Println(v.Role)
		if v.Role == "user" {
			resp = append(resp, qianfan.ChatCompletionUserMessage(v.Content))
		} else {
			resp = append(resp, qianfan.ChatCompletionAssistantMessage(v.Content))
		}
	}
	return resp
}

func (e QianFan) NewChat(messageData []chatModel.Message, c *gin.Context) {
	qianfan.GetConfig().AccessKey = access_key
	qianfan.GetConfig().SecretKey = secret_key

	chat := qianfan.NewChatCompletion(
		qianfan.WithModel("ERNIE-Bot-4"),
	)

	// 处理消息格式
	msgData := FormatChatMessage(messageData)

	resp, _ := chat.Stream(
		context.TODO(),
		&qianfan.ChatCompletionRequest{
			Messages: msgData,
		},
	)

	for {
		r, err := resp.Recv()
		if err != nil {
			panic(err)
		}
		if resp.IsEnd {
			break
		}
		chatResp := ChatResponse{
			Object:  "assistant",
			Created: r.Created,
			IsEnd:   resp.IsEnd,
			Result:  r.Result,
			Id:      r.Id,
			Model:   "qianfan",
		}
		c.SSEvent("result", chatResp)
		c.Writer.Flush()
	}

}

func (e QianFan) Text2Img(text string) {

}
